package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.MqOpsService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.util.MD5;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
@Slf4j
public class AlbumInfoListener {

    @Autowired
    private MqOpsService mqOpsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE)
            ,exchange =@Exchange(value = MqConst.EXCHANGE_TRACK)
            ,key = MqConst.ROUTING_TRACK_STAT_UPDATE))
    @SneakyThrows  //SneakyThrows可以绕开编译的时候的异常 但是真正在运行期间出现异常依然会抛出来
    public void listenTrackStatTypeUpdate(String content , Message message, Channel channel){
        //1.判断消息是否存在
        if (StringUtils.isEmpty(content)){
            return; //不用消费
        }
        //2，处理消息（todo）
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);

        //3.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //4.手动应答消息（将消息从队列中删除掉）
            mqOpsService.trackStatTypeUpdate(trackStatMqVo);
            channel.basicAck(deliveryTag,false);
        }catch (GuiguException e){
            String msgRetryKey = "msg:retry" + trackStatMqVo.getBusinessNo() ;  //业务去重的编号
            Long count = redisTemplate.opsForValue().increment(msgRetryKey);
            // 三次重试
            if (count >= 3){
                log.error("消息已经达到了重试{}次，请人工排查原因：{}",count,e.getMessage());
                //不能重试
                channel.basicNack(deliveryTag,false,false);
                redisTemplate.delete(msgRetryKey);
            }else {
                log.info("消息重试了{}次",count);
                channel.basicNack(deliveryTag,false,true);
            }
        } catch (Exception e) {
            log.error("签收消息时网络出现了故障，异常原因：{}",e.getMessage());
            channel.basicNack(deliveryTag,false,false);
        }

    }
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ALBUM_STAT_UPDATE)
            ,exchange =@Exchange(value = MqConst.EXCHANGE_ALBUM)
            ,key = MqConst.ROUTING_ALBUM_STAT_UPDATE))
    @SneakyThrows  //SneakyThrows可以绕开编译的时候的异常 但是真正在运行期间出现异常依然会抛出来
    public void listenAlbumStatTypeUpdate(String content , Message message, Channel channel){
        //1.判断消息是否存在
        if (StringUtils.isEmpty(content)){
            return; //不用消费
        }
        JSONObject jsonObject = JSONObject.parseObject(content);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //2.消费消息
        mqOpsService.albumStatTypeUpdate(jsonObject);
        //3.手动应答消息（将消息从队列中删除掉）
        channel.basicAck(deliveryTag,false);


    }
}
